#!/bin/sh
# Diapason Studio for Linux: installs itself in the applications menu, installs the page shipped with it,
# replaces it with a newer one from the website when there is one, then opens it in its own window.
VERSION="1.5.0"
BASE="https://diapasonstudio.netlify.app/"
SELF="$(readlink -f "$0")"
HERE="$(dirname "$SELF")"
SHARE="${XDG_DATA_HOME:-$HOME/.local/share}"
PROG="$SHARE/DiapasonStudio/programme"

LANGUE="${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}"; LANGUE="${LANGUE%%[_.@]*}"
fail() {
  MSG="$(case "$LANGUE" in en) echo "Diapason Studio could not start:";; es) echo "Diapason Studio no pudo iniciarse:";; de) echo "Diapason Studio konnte nicht gestartet werden:";; pt) echo "Não foi possível iniciar o Diapason Studio:";; *) echo "Diapason Studio n’a pas pu démarrer :";; esac) $1"
  echo "$MSG" >&2
  if command -v zenity >/dev/null 2>&1; then zenity --error --title="Diapason Studio" --text="$MSG" >/dev/null 2>&1
  elif command -v kdialog >/dev/null 2>&1; then kdialog --title "Diapason Studio" --error "$MSG" >/dev/null 2>&1
  elif command -v notify-send >/dev/null 2>&1; then notify-send "Diapason Studio" "$MSG"
  fi
  exit 1
}

# True when version $1 is greater than version $2
newer() {
  awk -v a="$1" -v b="$2" 'BEGIN { split(a, x, "."); split(b, y, "."); for (i = 1; i <= 3; i++) { if (x[i] + 0 > y[i] + 0) exit 0; if (x[i] + 0 < y[i] + 0) exit 1 } exit 1 }'
}

# fetch URL FILE SECONDS
fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL --max-time "$3" -o "$2" "$1" 2>/dev/null
  elif command -v wget >/dev/null 2>&1; then wget -q -T "$3" -O "$2" "$1" 2>/dev/null
  else return 1
  fi
}

# Run from the downloaded folder: copy the program next to its data, so that folder can be deleted
if [ "$HERE" != "$PROG" ]; then
  INSTALLED="$(sed -n 's/^VERSION="\(.*\)"$/\1/p' "$PROG/diapason-studio" 2>/dev/null)"
  if [ -z "$INSTALLED" ] || ! newer "$INSTALLED" "$VERSION"; then
    mkdir -p "$PROG" && cp -f "$HERE/diapason-studio" "$HERE/diapason.html" "$HERE/logo.svg" "$HERE/diapason-studio.png" "$PROG/" \
      && chmod +x "$PROG/diapason-studio" || fail "$(case "$LANGUE" in en) echo "cannot copy the program to";; es) echo "no se puede copiar el programa en";; de) echo "das Programm kann nicht kopiert werden nach";; pt) echo "não é possível copiar o programa para";; *) echo "impossible de copier le programme dans";; esac) $PROG."
  fi
  exec "$PROG/diapason-studio" "$@"
fi

# Applications menu entry
mkdir -p "$SHARE/applications"
DESKTOP="$SHARE/applications/diapason-studio.desktop"
ENTRY="[Desktop Entry]
Type=Application
Name=Diapason Studio
GenericName=Éditeur de présentations
GenericName[en]=Presentation editor
GenericName[es]=Editor de presentaciones
GenericName[de]=Präsentationseditor
GenericName[pt]=Editor de apresentações
Comment=Créer et présenter des diaporamas
Comment[en]=Create and present slide shows
Comment[es]=Crear y mostrar presentaciones
Comment[de]=Präsentationen erstellen und vorführen
Comment[pt]=Criar e exibir apresentações
Exec=\"$PROG/diapason-studio\"
Icon=$PROG/diapason-studio.png
Terminal=false
Categories=Office;Presentation;
StartupNotify=true"
if [ "$(cat "$DESKTOP" 2>/dev/null)" != "$ENTRY" ]; then
  printf '%s\n' "$ENTRY" > "$DESKTOP" && chmod +x "$DESKTOP"
  command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$SHARE/applications" >/dev/null 2>&1
fi

# Browser: a Chromium-based one opens a window without browser chrome; Firefox opens a normal window
BROWSER=""; KIND=""
for B in google-chrome-stable google-chrome microsoft-edge-stable microsoft-edge brave-browser brave chromium chromium-browser vivaldi-stable vivaldi; do
  if P="$(command -v "$B" 2>/dev/null)"; then BROWSER="$P"; KIND=chromium; break; fi
done
if [ -z "$BROWSER" ] && P="$(command -v firefox 2>/dev/null)"; then BROWSER="$P"; KIND=firefox; fi

# Snap browsers cannot read hidden folders like ~/.local: keep the page in the snap's own folder instead
SNAP_NAME=""
case "$(readlink -f "$BROWSER" 2>/dev/null)" in */snap) SNAP_NAME="$(basename "$BROWSER")" ;; esac
if [ -z "$SNAP_NAME" ] && [ -n "$BROWSER" ] && [ "$(wc -c < "$BROWSER")" -lt 100000 ] && grep -q "/snap/bin/" "$BROWSER" 2>/dev/null; then
  [ "$KIND" = firefox ] && SNAP_NAME=firefox || SNAP_NAME=chromium
fi
case "$SNAP_NAME" in chromium-browser) SNAP_NAME=chromium ;; esac
if [ -n "$SNAP_NAME" ]; then DIR="$HOME/snap/$SNAP_NAME/common/DiapasonStudio"; else DIR="$SHARE/DiapasonStudio"; fi
PAGE="$DIR/diapason.html"
VERFILE="$DIR/version.txt"
mkdir -p "$DIR" || fail "$(case "$LANGUE" in en) echo "cannot create the folder";; es) echo "no se puede crear la carpeta";; de) echo "der Ordner kann nicht erstellt werden:";; pt) echo "não é possível criar a pasta";; *) echo "impossible de créer le dossier";; esac) $DIR."

# Keep a newer version downloaded earlier; otherwise install the one shipped with the program
LOCAL=""
[ -f "$PAGE" ] && [ -f "$VERFILE" ] && LOCAL="$(tr -d ' \r\n' < "$VERFILE")"
if [ -z "$LOCAL" ] || newer "$VERSION" "$LOCAL"; then
  cp "$PROG/diapason.html" "$PAGE" || fail "$(case "$LANGUE" in en) echo "cannot copy the page to";; es) echo "no se puede copiar la página en";; de) echo "die Seite kann nicht kopiert werden nach";; pt) echo "não é possível copiar a página para";; *) echo "impossible de copier la page dans";; esac) $DIR."
  printf '%s\n' "$VERSION" > "$VERFILE"
  LOCAL="$VERSION"
fi
cp "$PROG/logo.svg" "$DIR/logo.svg" 2>/dev/null

# Download the latest page from the website when it is newer; silently does nothing when offline
STAMP="$(date +%s)"
TMP="$PAGE.tmp"
REMOTE=""
if fetch "${BASE}version.json?t=$STAMP" "$TMP" 4; then
  REMOTE="$(tr -d '\r\n' < "$TMP" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([0-9.]*\)".*/\1/p')"
fi
if [ -n "$REMOTE" ] && newer "$REMOTE" "$LOCAL"; then
  if fetch "${BASE}index.html?t=$STAMP" "$TMP" 30 && [ "$(wc -c < "$TMP")" -gt 10000 ] && grep -q "const APP_VERSION" "$TMP"; then
    mv -f "$TMP" "$PAGE" && printf '%s\n' "$REMOTE" > "$VERFILE"
  fi
fi
rm -f "$TMP"

URL="file://$(printf '%s' "$PAGE" | sed 's/%/%25/g; s/ /%20/g; s/#/%23/g; s/?/%3F/g')"

if [ "$KIND" = chromium ]; then
  # A dedicated profile keeps the saved presentation separate and opens a window without browser chrome
  nohup "$BROWSER" --app="$URL" --user-data-dir="$DIR/profil" --no-first-run --no-default-browser-check \
    --window-size=1440,900 >/dev/null 2>&1 &
elif [ "$KIND" = firefox ]; then
  nohup "$BROWSER" --new-window "$URL" >/dev/null 2>&1 &
elif command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$URL" >/dev/null 2>&1 &
else
  fail "$(case "$LANGUE" in en) echo "no browser found. Install Google Chrome, Chromium, Microsoft Edge or Firefox.";; es) echo "no se encontró ningún navegador. Instale Google Chrome, Chromium, Microsoft Edge o Firefox.";; de) echo "kein Browser gefunden. Installieren Sie Google Chrome, Chromium, Microsoft Edge oder Firefox.";; pt) echo "nenhum navegador encontrado. Instale o Google Chrome, Chromium, Microsoft Edge ou Firefox.";; *) echo "aucun navigateur trouvé. Installez Google Chrome, Chromium, Microsoft Edge ou Firefox.";; esac)"
fi
